package ReflectTest02;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/*
通过反射实现如下操作
Student s=new Student();
s.name="姜恒星";
s.age=30;
s.address="西安";
System.out.println(s);
 */
public class ReflectDemo01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //获取Class对象
        Class<?> c = Class.forName("Reflect.Student");

        //通过无参构造方法创建对象
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();
        System.out.println(obj);

        //s.name="姜恒星“
//        Field nameField = c.getField("name");//NoSuchFieldException
        Field nameField =c.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(obj,"姜恒星");
        System.out.println(obj);

        //s.age=30;
        Field ageField = c.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(obj,30);
        System.out.println(obj);

        //s.address="西安";
        Field addressField = c.getDeclaredField("address");
        addressField.setAccessible(true);
        addressField.set(obj,"西安");
        System.out.println(obj);
    }
}
